package org.jeecg.modules.solitaire_app.utils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * @Description: 公共模块
 * @Author: jeecg-boot
 * @Date:   2022-03-11
 * @Version: V1.0
 */
@Slf4j
@Api(tags="公共模块")
@RestController
@RequestMapping("/utils/utils")
public class UploadUtil {

    @Value("${uploadImage.path}")
    private String UPLOADPATH;

    @Value("${uploadImage.result_path}")
    private String RESULTPATH;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @AutoLog(value = "公共模块-文件上传")
    @ApiOperation(value="公共模块-文件上传", notes="公共模块-文件上传")
    @PostMapping("/uploadImage")
    public Result<?> uploadImage(@RequestParam(value = "file") MultipartFile file) {
        String uploadPath = this.UPLOADPATH;
        File uploadDirectory = new File(uploadPath);
        String fileName = null;
        String resultPath = null;
        if (uploadDirectory.exists()) {
            if (!uploadDirectory.isDirectory()) {
                uploadDirectory.delete();
            }
        } else {
            uploadDirectory.mkdir();
        }
        //这里支持多文件上传
        if (file != null) {
            BufferedOutputStream bufferedOutputStream = null;
            try {
                fileName = file.getOriginalFilename();
                String uploadFileName = fileName;
                //判断文件是否为图片文件
                if (fileName != null && !"".equalsIgnoreCase(fileName.trim())) {
                    File outFile = new File(uploadPath + "/" + uploadFileName);
                    FileUtils.copyInputStreamToFile(file.getInputStream(), outFile);
                }
                //返回路径
                resultPath = this.RESULTPATH + uploadFileName;
                return Result.ok(resultPath);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("服务器响应失败");
            } finally {
                try {
                    if (bufferedOutputStream != null) {
                        bufferedOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return Result.error("服务器崩溃");
                }
            }
        } else {
            return Result.error("图片不能为空");
        }
    }
}
